<template>
    <elm-page-bb>
        <el-form ref="model" :model="model" size="small" label-width="80px">
            <el-form-item label="组织机构" prop="dept_id">
                <elm-org v-model="model.dept_id" clearable :disabled="model.ei_id!=null"></elm-org>
            </el-form-item>
          <elm-row>
            <el-form-item label="用户姓名" prop="nick_name" :rules="[{ required: true, message: '姓名必须填写'}]">
              <el-input v-model="model.nick_name" :disabled="model.ei_id!=null"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" prop="sex">
                <el-select v-model="model.sex" placeholder="请选择性别" :disabled="model.ei_id!=null">
                  <el-option key="男" label="男" value="男"></el-option>
                  <el-option key="女" label="女" value="女"></el-option>
                </el-select>
            </el-form-item>
          </elm-row>
           <elm-row>
             <el-form-item label="认证账号" prop="user_name" :rules="[{ required: true, message: '账号必须填写'}]">
               <el-input v-model="model.user_name" :disabled="model.ei_id!=null">
                 <template slot="append">.{{elm.info.tenant}}</template>
               </el-input>
             </el-form-item>
             <el-form-item label="认证密码">
               <el-input readonly v-model="model.password" type="text" v-if="show_pwd"></el-input>
               <el-button size="small"  type="danger" style="width: 100%" @click="repwd" plain v-else>重置密码</el-button>
             </el-form-item>
           </elm-row>
            <elm-row>
              <el-form-item label="联系电话" prop="phonenumber">
                <el-input v-model="model.phonenumber" :disabled="model.ei_id!=null"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="model.email" :disabled="model.ei_id!=null"></el-input>
              </el-form-item>
            </elm-row>
            <el-form-item label="头像">
                <elm-upload v-if="model.ei_id==null" module_name="sys_user_avatar" :rel_id="model.id" :multiple="false" :limit="1"  list-type="picture" tip=" "></elm-upload>
                <elm-fileview v-if="model.ei_id!=null" module_name="biz_hrm_ei_basic_avatar" :rel_id="model.ei_id" :multiple="false" :limit="1"  list-type="picture" tip=" "></elm-fileview>
            </el-form-item>
          <elm-row>
            <el-form-item label="归属员工" prop="emp_code">
              <elm-ei v-model="model.emp_code" :input-add="false"></elm-ei>
            </el-form-item>
            <el-form-item label="是否启用">
              <el-switch v-model="model.status" active-color="#13ce66" inactive-color="#ff4949" active-value="启用" inactive-value="禁用"></el-switch>
            </el-form-item>
          </elm-row>

        </el-form>
        <template #bottom>
            <el-button type="success" size="small" @click="submit">立即保存</el-button>
            <el-button size="small" @click="close">取消</el-button>
        </template>
    </elm-page-bb>
</template>

<script>
    export default {
        extends: elmVueBase,
        data() {
            return {
                model: { status: "启用", sex: "男", telephone: "", id: elm.newGuid(),password:this.g_password(8), init_password:1},
              show_pwd:true
            }
        },
        created() {
          if(this.request.model!=undefined)
          {
            this.show_pwd=false;
          }
        },
        methods: {
            async submit() {
                await this.$refs["model"].validate();
                var res = await elm.post('/system/user/Any', { "user_name": this.model.user_name, "id": this.model.id });
                if (res == true) {
                    this.$message.error('账户（' + this.model.user_name + '）已被注册!');
                }
                else {
                  var res = await elm.post('/system/user/Upsert', this.model);
                  if (res == true) {
                    this.v('保存成功。')
                    this.close();
                    this.request.callVue.tablebinding();
                  } else {
                    this.error('保存失败，请稍后尝试。');
                  }
                }
            },
          repwd()
          {
            this.$confirm('确认要重置密码?此操作会为用户初始化一个随机密码，下次登录将强制修改密码。', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
                .then(async () =>{
                  this.model.password=this.g_password(8);
                  var res = await elm.post('/system/user/ReSetPassword', {"id": this.model.id,password:this.model.password });
                  if(res>0)
                  {
                    this.show_pwd=true;
                    this.v("密码已重置为"+this.model.password+"。")
                  }
                  else
                  {
                    this.error('密码已重置失败，请稍后尝试。');
                  }
                }).catch(()=> {
            });
          },
            g_password(length) {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$%&*-_=+<>';
            let result = '';
            const charactersLength = characters.length;
            const hasNumber = /[0-9]/;
            const hasUpper = /[A-Z]/;
            const hasLower = /[a-z]/;
            const hasSpecial = /[@#$%&*-_=+<>]/;

            // Ensure the password contains at least one of each required character type
            result += characters.charAt(Math.floor(Math.random() * charactersLength)); // Random character
            result += characters.charAt(Math.floor(Math.random() * 10) + '0'.charCodeAt(0) - '0'.charCodeAt(0)); // Random number
            result += characters.charAt(Math.floor(Math.random() * 26) + 'A'.charCodeAt(0) - 'A'.charCodeAt(0)); // Random uppercase letter
            result += characters.charAt(Math.floor(Math.random() * 26) + 'a'.charCodeAt(0) - 'a'.charCodeAt(0)); // Random lowercase letter
            result += characters.charAt(Math.floor(Math.random() * 32) + '@#$%&*-_=+<>'.charCodeAt(0) - '!'.charCodeAt(0)); // Random special character

            // Fill the rest of the password length with random characters
            for (let i = result.length; i < length; i++) {
              result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }

            // Shuffle the resulting password to ensure randomness
            result = result.split('').sort(() => Math.random() - 0.5).join('');

            // Optionally, verify that the password still contains at least one of each required character type
            if (!hasNumber.test(result) || !hasUpper.test(result) || !hasLower.test(result) || !hasSpecial.test(result)) {
              // If not, regenerate the password (should rarely happen due to shuffling)
              return this.g_password(length);
            }

            return result;
          }
        }
    }
</script>

<style scoped>
</style>